package com.icw.configuration.database;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.aop.Advisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import com.icw.configuration.ConstSettings;
import com.icw.decoupling.defi.proxy.GenericSrvProxy;
import com.icw.utility.IcwUtils;

@Configuration
public class TransactionManagerConfig {

	private static final int TX_METHOD_TIMEOUT = 30;

	@Bean
	public TransactionInterceptor txAdvice(PlatformTransactionManager transactionManager) {
		// 1. read only transaction
		RuleBasedTransactionAttribute readOnlyRule = new RuleBasedTransactionAttribute();
		readOnlyRule.setReadOnly(true);
		readOnlyRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		readOnlyRule.setTimeout(TX_METHOD_TIMEOUT);
		// 2. writable transaction
		RuleBasedTransactionAttribute requireRule = new RuleBasedTransactionAttribute();
		requireRule.setReadOnly(false);
		requireRule.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
		requireRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		requireRule.setTimeout(TX_METHOD_TIMEOUT);
		// 3. set rules
		Map<String, TransactionAttribute> txMap = new HashMap<>();
		// ----
		txMap.put("one", readOnlyRule);
		txMap.put("delete*", requireRule);
		txMap.put("save", requireRule);
		txMap.put("save*", requireRule);
		txMap.put("update*", requireRule);
		// ----
		txMap.put("exec", requireRule);
		txMap.put("exec*", requireRule);
		txMap.put("query*", readOnlyRule);
		txMap.put("read*", readOnlyRule);
		txMap.put("invoke*", readOnlyRule);
		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		source.setNameMap(txMap);
		// 4. return Transaction
		return new TransactionInterceptor(transactionManager, source);
	}

	@Bean
	public Advisor txAdviceAdvisor(TransactionInterceptor txAdvice) throws Exception {
		return IcwUtils.cutInterface(txAdvice, GenericSrvProxy.class, ConstSettings.FIRST_ORDER);
	}
}